package com.hp.util;

import com.hp.bean.Syslog;
import com.hp.service.SyslogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

//	@Aspect 注解 作为切面被读取
@Aspect
public class LogAopAction {
    //注入service,用来将日志信息保存在数据库
    @Autowired
    private SyslogService logService;


    //配置接入点
    //第一种，通过路径进行设置切入点
//    @Pointcut(value = "execution(* com.hp.controller..*.*(..))")
//    public void logAspect(){};
    //通过自定义的注解作切入点
    @Pointcut("@annotation(com.hp.util.Log)")
    public void logAspect2() {
    }

    ;

    @Around("logAspect2()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Syslog log = new Syslog();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.setUserid(getUserID(request.getSession()));
        //获取系统时间
        log.setDates(new SimpleDateFormat().format(new Date()));
        //获取系统ip
        String ip = IPUtil.getIPAddress(request);
        log.setIp(ip);
        //方法通知前获取时间
        long start = System.currentTimeMillis();
        // 获取代理对象
        Object target = joinPoint.getTarget();
        // 拦截的方法名称。当前正在执行的方法
        String methodName = joinPoint.getSignature().getName();
        // 拦截的方法参数
        Object[] args = joinPoint.getArgs();
        // 拦截的放参数类型
        Signature sig = joinPoint.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Class[] parameterTypes = msig.getMethod().getParameterTypes();
        Object object = null;
        Method method = null;
        try {
            method = target.getClass().getMethod(methodName, parameterTypes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断该方法在代理对象中是否存在
        if (null != method) {//存在
            // 判断是否包含自定义的注解，说明一下这里的Log就是我自己自定义的注解
            if (method.isAnnotationPresent(Log.class)) {
                Log logger = method.getAnnotation(Log.class);
                log.setModule(logger.module());
                log.setMethod(logger.methods());
                try {
                    //执行具体的操作
                    object = joinPoint.proceed();
                    long end = System.currentTimeMillis();
                    log.setresponseDate("" + (end - start));
                    log.setCommit("执行成功");
                    logService.insertSyslog(log);
                } catch (Throwable e) {
                    long end = System.currentTimeMillis();
                    log.setresponseDate("" + (end - start));
                    log.setCommit("执行失败");
                    logService.insertSyslog(log);
                }
            } else { //没有包含注解
                object = joinPoint.proceed();
            }
        } else { //不需要拦截直接执行
            object = joinPoint.proceed();
        }
        return object;
    }

    public String getUserID(HttpSession session) {
        //判断 客服
        if (session.getAttribute("customerservice") != null && (!(session.getAttribute("customerservice") + "").equals(""))) {
            return "客服：" + session.getAttribute("cname").toString();
        } else if (session.getAttribute("master") != null && (!(session.getAttribute("master") + "").equals(""))) {
            return "工程师：" + session.getAttribute("mname").toString();
        } else if (session.getAttribute("phone") != null && (!(session.getAttribute("phone") + "").equals(""))) {
            return "客户：" + session.getAttribute("phone").toString();
        } else {
            return "未登陆";
        }
    }

}
